#include "stm32f10x.h"
#include "motor.h"
#include "uart.h"
#include <stdio.h>

// 全局变量 - 在这里定义
uint8_t current_cmd = 'S';  // 默认停止状态

// 函数声明
void SystemClock_Config(void);

int main(void)
{
    // 系统初始化
    SystemClock_Config();
    
    // 初始化各个模块
    USART_SendString(USART1, (uint8_t*)"\r\n=== STM32 Smart Car - Motor Control Test ===\r\n");
    USART_SendString(USART1, (uint8_t*)"Initialize system...\r\n");
    
    // 配置串口
    UART1_Configuration();       // 调试串口
    UART3_Configuration();       // 命令接收串口
    
    // 初始化电机GPIO
    USART_SendString(USART1, (uint8_t*)"Initialize Motor GPIO...\r\n");
    Motor_GPIO_Configuration();
    
    // 配置中断
    USART_SendString(USART1, (uint8_t*)"Configure interrupt...\r\n");
    NVIC_Configuration();
    
    // 初始停止状态
    Motor_Stop();
    
    // 显示帮助信息
    USART_SendString(USART1, (uint8_t*)"\n=== Control Commands ===\r\n");
    USART_SendString(USART1, (uint8_t*)"f - Forward (Both wheels)\r\n");
    USART_SendString(USART1, (uint8_t*)"s - Backward (Both wheels)\r\n");
    USART_SendString(USART1, (uint8_t*)"l - Turn Left (Right wheel only)\r\n");
    USART_SendString(USART1, (uint8_t*)"r - Turn Right (Left wheel only)\r\n");
    USART_SendString(USART1, (uint8_t*)"0 - Stop\r\n");
    USART_SendString(USART1, (uint8_t*)"d - Debug (Show motor status)\r\n");
    USART_SendString(USART1, (uint8_t*)"\nWaiting for commands...\r\n");
    
    // 简单测试：前进2秒，然后停止 - 已注释以避免干扰
    // USART_SendString(USART1, (uint8_t*)"\n=== Test: Forward for 2 seconds ===\r\n");
    // Motor_Forward();
    // Delay(0xFFFFF);
    // Delay(0xFFFFF);
    // Motor_Stop();
    // USART_SendString(USART1, (uint8_t*)"Test completed! Now waiting for serial commands...\r\n");
    
    while (1)
    {
        // 主循环中保持运行
        Delay(0x7FFFF);
    }
}

// 系统时钟配置
void SystemClock_Config(void)
{
    // STM32F103C8T6的典型配置
    RCC_DeInit();
    RCC_HSEConfig(RCC_HSE_ON);  // 开启外部高速时钟
    while (RCC_GetFlagStatus(RCC_FLAG_HSERDY) == RESET);  // 等待HSE稳定
    
    RCC_HCLKConfig(RCC_SYSCLK_Div1);  // AHB时钟 = 系统时钟
    RCC_PCLK1Config(RCC_HCLK_Div2);    // APB1时钟 = AHB时钟/2
    RCC_PCLK2Config(RCC_HCLK_Div1);    // APB2时钟 = AHB时钟
    
    // 配置PLL
    RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);  // 8MHz * 9 = 72MHz
    RCC_PLLCmd(ENABLE);  // 使能PLL
    while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET);  // 等待PLL稳定
    
    RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);  // 系统时钟源为PLL
    while (RCC_GetSYSCLKSource() != 0x08);  // 确保PLL作为系统时钟
}